package whf.framework.security.web;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import whf.framework.entity.AbstractEntity;
import whf.framework.security.entity.Dept;
import whf.framework.security.entity.Group;
import whf.framework.security.entity.User;
import whf.framework.security.service.DeptServiceImp;
import whf.framework.security.service.GroupServiceImp;
import whf.framework.security.service.UserServiceImp;
import whf.framework.web.struts.WebData;
import whf.framework.web.struts.WebDispatchAction;
import whf.framework.web.struts.WebForward;

/**
 * @author wanghaifeng
 * @email king@126.com
 * @modify 2006-05-31
 */
public class GroupAction extends WebDispatchAction {

	public WebForward prepareGroupUser(AbstractEntity webEntity, WebData data) throws Exception{
		Group group = GroupServiceImp.getGroupService().findByPrimaryKeyWithoutLazy(webEntity.getId());
		String selectedUserIds = "0";
		for(User u: group.getUsers()){
			selectedUserIds += ","+u.getId();
		}
		group.setWebMethod("groupUser");
		data.setAttribute(group);
		data.setAttribute("groupUsers", group.getUsers());
		long deptId = data.getLongParameter("deptId", 0);
		if(deptId > 0){
			Dept dept = DeptServiceImp.getDeptService().findByPrimaryKey(deptId);
			data.setAttribute("dept", dept);
			List<User> users = UserServiceImp.getUserService().find("t.dept=? and t.id not in("+selectedUserIds+")", dept);
			data.setAttribute("users", users);
		} else {
			List<User> users = UserServiceImp.getUserService().find("t.id not in("+selectedUserIds+")");
			data.setAttribute("users", users);
		}
		return data.forward("groupUser");
	}
	
	public WebForward groupUser(AbstractEntity webEntity, WebData data) throws Exception{
		Group group = (Group)GroupServiceImp.getGroupService().findByPrimaryKeyWithoutLazy(webEntity.getId());
		Set<User> users = group.getUsers();
		long[] selectedUserIds = data.getLongParameters("selectedUser", 0);
		boolean changed = false;
		if(selectedUserIds == null){
			if(users.size() > 0){
				users.clear();
				changed = true;
			}
		} else {
			for(Iterator<User> it = users.iterator(); it.hasNext(); ){
				User u = (User)it.next();
				boolean found = false;
				for(long sid: selectedUserIds){
					if(u.getId() == sid){
						found = true;
						break;
					}
				}
				if(!found){
					it.remove();
					changed = true;
				}
			}
			for(long sid: selectedUserIds){
				if(sid == 0) continue;
				boolean found = false;
				for(User u: users){
					if(u.getId() == sid){
						found = true;
						break;
					}
				}
				if(!found){
					users.add(UserServiceImp.getUserService().findByPrimaryKey(sid));
					changed = true;
				}
			}
		}
		if(changed){
			GroupServiceImp.getGroupService().update(group);
		}
		return prepareGroupUser(webEntity, data);
	}
} 